<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上映管理</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
        }

        .toolbar {
            margin-bottom: 20px;
        }

        .dialog-footer {
            text-align: right;
            margin-top: 20px;
        }

        .seat-selection {
            max-width: 600px;
            margin: 50px auto;
        }

        .seat-row {
            display: flex;
            justify-content: space-around;
            margin-bottom: 10px;
        }

        .seat {
            width: 30px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid #ddd;
            cursor: pointer;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgb(64, 158, 255);
            color: white;
        }

        .seat.selected {
            background-color: red;
            cursor: not-allowed;
        }

        .seat.available {
            background-color: green;
        }

        .seat i {
            margin-right: 5px;
        }

        .el-table .el-button {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="toolbar">
            <el-input placeholder="搜索上映信息" v-model="searchKeyword" style="width: 200px;"></el-input>
            <el-button type="primary" size="small" @click="handleAddShowtime">添加上映</el-button>
        </div>
        <el-table :data="showtimes" stripe>
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="movie.title" label="电影名称"></el-table-column>
            <el-table-column label="电影封面" width="100">
                <template slot-scope="scope">
                    <img :src="scope.row.movie.poster" alt="电影封面" style="width: 50px; height: 50px;">
                </template>
            </el-table-column>
            <el-table-column prop="hall.name" label="影厅名称"></el-table-column>
            <el-table-column prop="startTime" label="开始时间"></el-table-column>
            <el-table-column prop="endTime" label="结束时间"></el-table-column>
            <el-table-column prop="price" label="价格"></el-table-column>
            <el-table-column prop="createdAt" label="创建时间"></el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
                    <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalShowtimes">
            </el-pagination>
        </div>
    </el-card>

    <el-dialog :title="isEditMode ? '编辑上映' : '添加上映'" :visible.sync="dialogVisible">
        <el-form :model="currentShowtime" :rules="rules" ref="showtimeForm" label-width="100px">
            <el-form-item label="电影" prop="movieId">
                <el-select v-model="currentShowtime.movieId" placeholder="请选择电影">
                    <el-option
                            v-for="movie in movies"
                            :key="movie.id"
                            :label="movie.title"
                            :value="movie.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="影厅" prop="hallId">
                <el-select v-model="currentShowtime.hallId" placeholder="请选择影厅" @change="fetchSeatsLayout">
                    <el-option
                            v-for="hall in halls"
                            :key="hall.id"
                            :label="hall.name"
                            :value="hall.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="座位布局">
                <div v-if="currentShowtime.seatsLayout" class="seat-selection">
                    <div v-for="(row, rowIndex) in currentShowtime.seatsLayout" :key="rowIndex" class="seat-row">
                        <div v-for="(seat, seatIndex) in row" :key="seatIndex" class="seat"
                             :class="{'selected': seat.selected, 'available': !seat.selected}"
                             @click="toggleSeatSelection(rowIndex, seatIndex)"
                             :style="{cursor: seat.selected ? 'not-allowed' : 'pointer'}">
                            <i class="el-icon-potato-strips"></i>
                        </div>
                    </div>
                </div>
                <span v-else>请选择影厅以查看座位布局</span>
            </el-form-item>
            <el-form-item label="状态" prop="status" style="display: none;">
                <el-input v-model="currentShowtime.status" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
                <el-date-picker v-model="currentShowtime.startTime" type="datetime"
                                placeholder="选择开始时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-date-picker v-model="currentShowtime.endTime" type="datetime"
                                placeholder="选择结束时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="价格" prop="price">
                <el-input v-model.number="currentShowtime.price" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                showtimes: [],
                totalShowtimes: 0,
                pageSize: 5,
                currentPage: 1,
                dialogVisible: false,
                currentShowtime: {},
                isEditMode: false,
                movies: [],
                halls: [],
                rules: {
                    movieId: [
                        {required: true, message: '请选择电影', trigger: 'change'}
                    ],
                    hallId: [
                        {required: true, message: '请选择影厅', trigger: 'change'}
                    ],
                    startTime: [
                        {required: true, message: '请选择开始时间', trigger: 'change'}
                    ],
                    endTime: [
                        {required: true, message: '请选择结束时间', trigger: 'change'}
                    ],
                    price: [
                        {required: true, message: '请输入价格', trigger: 'blur'},
                        {type: 'number', message: '价格必须为数字', trigger: 'blur'}
                    ],
                    status: [
                        {required: false} // 状态字段是可选的
                    ]
                }
            };
        },
        watch: {
            searchKeyword(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.currentPage = 1; // 重置当前页码为1
                    this.fetchShowtimes(); // 重新获取上映数据
                }
            },
            currentPage(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchShowtimes(); // 重新获取上映数据
                }
            },
            pageSize(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchShowtimes(); // 重新获取上映数据
                }
            }
        },
        methods: {
            fetchShowtimes() {
                axios.get('/showtime?operation=findShowtimesByPageAndMovieId', {
                    params: {
                        keyword: this.searchKeyword,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.showtimes = data.data; // 更新数据字段为 data.data
                        this.totalShowtimes = data.total;
                    } else {
                        this.$message.error('获取上映列表失败');
                    }
                }).catch(error => {
                    console.error('获取上映列表失败:', error);
                    this.$message.error('获取上映列表失败');
                });
            },
            fetchMovies() {
                return axios.get('/movie?operation=getAllMovies').then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.movies = data;
                    } else {
                        this.$message.error('获取电影列表失败');
                    }
                }).catch(error => {
                    console.error('获取电影列表失败:', error);
                    this.$message.error('获取电影列表失败');
                });
            },
            fetchHalls() {
                return axios.get('/hall?operation=getAllHalls').then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.halls = data;
                    } else {
                        this.$message.error('获取影厅列表失败');
                    }
                }).catch(error => {
                    console.error('获取影厅列表失败:', error);
                    this.$message.error('获取影厅列表失败');
                });
            },
            fetchSeatsLayout(hallId) {
                const hall = this.halls.find(hall => hall.id === hallId);
                if (hall) {
                    // 解析 seatsLayout
                    this.currentShowtime.seatsLayout = JSON.parse(hall.seatsLayout).map(row =>
                        row.map(seat => ({...seat, selected: false}))
                    );
                    // 更新 status 字段
                    this.updateStatus();
                } else {
                    this.currentShowtime.seatsLayout = null;
                    this.currentShowtime.status = '';
                }
            },
            handleAddShowtime() {
                this.isEditMode = false;
                this.currentShowtime = {
                    movieId: '',
                    hallId: '',
                    startTime: '',
                    endTime: '',
                    price: '',
                    status: '',
                    seatsLayout: null
                };
                this.fetchMovies(); // 获取电影列表
                this.fetchHalls(); // 获取影厅列表
                this.dialogVisible = true;
            },
            handleEdit(showtime) {
                this.isEditMode = true;
                this.currentShowtime = Object.assign({}, showtime);
                Promise.all([this.fetchMovies(), this.fetchHalls()]).then(() => {
                    // 解析 status 字段中的选中的座位
                    if (this.currentShowtime.status) {
                        const selectedSeats = JSON.parse(this.currentShowtime.status);
                        const hall = this.halls.find(hall => hall.id === this.currentShowtime.hallId);
                        if (hall) {
                            // 解析 seatsLayout
                            this.currentShowtime.seatsLayout = JSON.parse(hall.seatsLayout).map(row =>
                                row.map(seat => ({...seat, selected: false}))
                            );
                            selectedSeats.forEach(seat => {
                                const row = this.currentShowtime.seatsLayout[seat.row - 1];
                                if (row) {
                                    const col = row[seat.col - 1];
                                    if (col) {
                                        col.selected = seat.selected;
                                    }
                                }
                            });
                        } else {
                            this.currentShowtime.seatsLayout = null;
                            this.currentShowtime.status = '';
                        }
                    } else {
                        this.fetchSeatsLayout(showtime.hallId); // 获取座位布局
                    }

                    this.dialogVisible = true;
                });
            },
            handleSave() {
                this.$refs.showtimeForm.validate(valid => {
                    if (valid) {
                        // 将 seatsLayout 转换为 JSON 并赋值给 status
                        this.currentShowtime.status = JSON.stringify(this.currentShowtime.seatsLayout.flat().filter(seat => seat.selected));

                        const url = this.isEditMode ? '/showtime?operation=updateShowtime' : '/showtime?operation=addShowtime';
                        axios.post(url, this.currentShowtime)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success(this.isEditMode ? '上映信息更新成功' : '上映添加成功');
                                    this.fetchShowtimes();
                                } else {
                                    this.$message.error(this.isEditMode ? '上映信息更新失败' : '上映添加失败');
                                }
                            })
                            .catch(error => {
                                console.error(this.isEditMode ? '上映信息更新失败:' : '上映添加失败:', error);
                                this.$message.error(this.isEditMode ? '上映信息更新失败' : '上映添加失败');
                            });
                        this.dialogVisible = false;
                    }
                });
            },
            handleDelete(showtime) {
                this.$confirm('此操作将永久删除该上映信息, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/showtime?operation=deleteShowtime&id=' + showtime.id)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('上映信息删除成功');
                                this.fetchShowtimes();
                            } else {
                                this.$message.error('上映信息删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('上映信息删除失败:', error);
                            this.$message.error('上映信息删除失败');
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            toggleSeatSelection(rowIndex, seatIndex) {
                if (!this.currentShowtime.seatsLayout[rowIndex][seatIndex].selected) {
                    this.currentShowtime.seatsLayout[rowIndex][seatIndex].selected = !this.currentShowtime.seatsLayout[rowIndex][seatIndex].selected;
                    this.updateStatus();
                }
            },
            updateStatus() {
                if (this.currentShowtime.seatsLayout) {
                    const selectedSeats = this.currentShowtime.seatsLayout.flat().filter(seat => seat.selected);
                    this.currentShowtime.status = JSON.stringify(selectedSeats);
                } else {
                    this.currentShowtime.status = '';
                }
            }
        },
        mounted() {
            this.fetchShowtimes();
        }
    });
</script>

</body>
</html>